package com.gmlive.common.ui.widget;

import android.graphics.Rect;
import android.view.View;

import androidx.recyclerview.widget.RecyclerView;

import static com.gmlive.common.ui.util.DisplayHelper.dpToPx;

/**
 * RecyclerView的网格分割线
 *
 * @作者: 姜志敏
 * @日期: 2019-11-21
 */
public class GridItemDecoration extends RecyclerView.ItemDecoration {
    private int mSpanCount;

    // 水平间距
    private int mHSpace;
    // 垂直间距
    private int mVSpace;

    public GridItemDecoration(int spanCount, int hSpaceDp, int vSpaceDp) {
        mSpanCount = spanCount;
        mHSpace = dpToPx(hSpaceDp);
        mVSpace = dpToPx(vSpaceDp);
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        int childCount = parent.getAdapter().getItemCount();
        int position = parent.getChildAdapterPosition(view);
        if (isFirstRow(position)) {
            outRect.top = 0;
        } else {
            outRect.top = mVSpace / 2;
        }

        if (isFirstColumn(position)) {
            outRect.left = 0;
        } else {
            outRect.left = mHSpace / 2;
        }

        if (isLastRow(position, childCount)) {
            outRect.bottom = 0;
        } else {
            outRect.bottom = mVSpace / 2;
        }

        if (isLastColumn(position)) {
            outRect.right = 0;
        } else {
            outRect.right = mHSpace / 2;
        }
    }

    private boolean isLastRow(int position, int childCount) {
        int rowCount = getRowCount(childCount);

        return (rowCount - 1) * mSpanCount <= position && position < rowCount * mSpanCount;
    }

    private boolean isLastColumn(int position) {
        return (position + 1) % mSpanCount == 0;
    }

    private boolean isFirstRow(int position) {
        return position < mSpanCount;
    }

    private boolean isFirstColumn(int position) {
        return position % mSpanCount == 0;
    }

    private int getRowCount(int childCount) {
        return childCount / mSpanCount + (childCount % mSpanCount == 0 ? 0 : 1);
    }
}
